﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

using System.Runtime.InteropServices;

using CCL.Utility;
using CCL.SocketMessage;


namespace Client
{
    public class Connector
    {
        // Server IP, Port Number
        private const string m_ip = "127.0.0.1";
        private const int m_port = 8192;

        private IPEndPoint m_ipEndPoint;
        private Socket m_socket;

        // 클라이언트가 서버에 접속되어있는가?
        private bool m_bConnect = false;

        //private PacketParsingFactory m_ppFactory = new PacketParsingFactory();

        public bool IsConnect
        {
            get { return m_bConnect; }
        }

        public Message Execute(byte[] sendBytes)
        {
            Message retVal = null;

            ConnectServer();

            SendMsg(sendBytes);

            retVal = RecvMsg();

            CloseSocket();

            return retVal;
        }

        private void ConnectServer()
        {
            try
            {
                m_ipEndPoint = new IPEndPoint(IPAddress.Parse(m_ip), m_port);
                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_socket.Connect(m_ipEndPoint);
            }
            catch (SocketException)
            {
                //MessageBox.Show(e.Message);
                return;
            }
            m_bConnect = true;
        }

        private void CloseSocket()
        {
            if (m_bConnect == true)
            {
                m_socket.Close();
                m_bConnect = false;
            }
        }

        private void SendMsg(byte[] data)
        {
            if (m_bConnect == false)
            {
                return;
            }

            // 메세지 타입과 데이터를 클래스 형태로 파싱
            //PacketObject packet = m_ppFactory.ParsingMsg(type, data);

            // 바이트 형태의 메세지배열을 생성
            //byte[] msg = new byte[packet.Length];

            // PacketObject 클래스 전체를 byte 단위로 파싱
            // 서버로 msg 를 send.

            m_socket.Send(data);
        }

        private Message RecvMsg()
        {
            if (m_bConnect == false)
            {
                return null;
            }

            byte[] headerBytes = new byte[17];
            m_socket.Receive(headerBytes);
            Header header = new Header(headerBytes);

            byte[] bodyBytes = new byte[header.BodyLength];
            m_socket.Receive(bodyBytes);

            Message msg = Message.MessageResponseBuilder(header, bodyBytes);

            return msg;

            /*
            byte[] recvByte = new byte[1024];

            m_socket.Receive(recvByte);

            return recvByte;
             */
        }
    }
}
